package personal.lijun.skeleton.springcloud.serviceprovider.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import personal.lijun.skeleton.spring.springcloud.serviceprovider.data.CalendarUser;
import personal.lijun.skeleton.spring.springcloud.serviceprovider.data.Role;
import personal.lijun.skeleton.spring.springcloud.serviceprovider.service.CalendarUsersService;
import personal.lijun.skeleton.springcloud.common.data.ApiResultPrimitiveValue;
import personal.lijun.skeleton.springcloud.dataaccess.dao.CalendarUsersMapper;
import personal.lijun.skeleton.springcloud.dataaccess.data.CalendarUsers;
import personal.lijun.skeleton.springcloud.dataaccess.data.CalendarUsersExample;
import personal.lijun.skeleton.springcloud.utils.validate.DirtyDataException;
import personal.lijun.skeleton.springcloud.utils.validate.ParamValid;
import personal.lijun.skeleton.springcloud.utils.validate.ParamValidException;
import personal.lijun.skeleton.springcloud.utils.validate.ValidGroups;


import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service("CalendarUsersService")
public class CalendarUsersServiceImpl implements CalendarUsersService {

    @Resource
    private CalendarUsersMapper calendarUsersMapper;

    /**
     * 保存用户
     *
     * @param record 用户信息
     */
    @ParamValid
    @Transactional()
    public CalendarUser save(@ValidGroups(groups = {CalendarUser.INSERT_GROUP.class}) CalendarUser record) {
        Long id = record.getId();
        if (id != null)
            this.updateCalendarUsers(record);
        else {
            this.addNewCalendarUsers(record);
        }
        return record;
    }

    /**
     * 增加一个新用户信息
     *
     * @param record
     * @return
     */
    @ParamValid
    @Transactional()
    public CalendarUser addNewCalendarUsers(@ValidGroups(groups = {CalendarUser.INSERT_GROUP.class}) CalendarUser record) {
        assertNewUserEmailIsUsed(record.getEmail());
        CalendarUsers calendarUsers = new CalendarUsers();
        BeanUtils.copyProperties(record, calendarUsers);
        calendarUsersMapper.insertSelective(calendarUsers);
        record.setId(calendarUsers.getId());
        return record;
    }

    /**
     * 更新指定用户信息
     *
     * @param record
     * @return
     */
    @ParamValid
    @Transactional()
    public CalendarUser updateCalendarUsers(@ValidGroups(groups = {CalendarUser.UPDATE_GROUP.class}) CalendarUser record) {
        assertUpdateUserEmailIsUsed(record.getEmail(), record.getId());
        CalendarUsers calendarUsers = new CalendarUsers();
        BeanUtils.copyProperties(record, calendarUsers);
        int updateRow = calendarUsersMapper.updateByPrimaryKeySelective(calendarUsers);
        if (updateRow == 1)
            return record;
        return null;
    }

    protected void assertNewUserEmailIsUsed(String email) {
        CalendarUsersExample calendarUsersExample = new CalendarUsersExample();
        CalendarUsersExample.Criteria criteria = calendarUsersExample.createCriteria();
        criteria.andEmailEqualTo(email);

        int count = calendarUsersMapper.countByExample(calendarUsersExample);
        if (count > 0) {
            throw new ParamValidException("此email已经被其他用户注册过了！");
        }
    }

    protected void assertUpdateUserEmailIsUsed(String email, Long userId) {
        CalendarUsersExample calendarUsersExample = new CalendarUsersExample();
        CalendarUsersExample.Criteria criteria = calendarUsersExample.createCriteria();
        criteria.andEmailEqualTo(email);

        List<CalendarUsers> usersList = calendarUsersMapper.selectByExample(calendarUsersExample);
        if (usersList.size() > 1) {
            throw new ParamValidException("此email已经被其他用户注册过了！");
        } else if (usersList.size() == 1) {
            CalendarUsers calendarUsers = usersList.get(0);
            if (!calendarUsers.getId().equals(userId)) {
                throw new ParamValidException("此email已经被其他用户注册过了！");
            }
        }
    }

    /**
     * 根据id删除指定用户
     *
     * @param id 用户id
     * @return
     */
    public Integer deleteCalendarUsersById(Long id) {
        return calendarUsersMapper.deleteByPrimaryKey(id);
    }

    /**
     * 查询指定id的用户信息
     *
     * @param id 用户id
     * @return
     */
    public CalendarUser getCalendarUsersById(Long id) {
        CalendarUsers calendarUsers = calendarUsersMapper.selectByPrimaryKey(id);
        CalendarUser calendarUser = new CalendarUser();
        BeanUtils.copyProperties(calendarUsers, calendarUser);
        return calendarUser;
    }

    /**
     * 根据用户email，查询用户
     * @param email
     * @return
     */
    public CalendarUser findUserByEmail(String email) {
        CalendarUsersExample calendarUsersExample = new CalendarUsersExample();
        CalendarUsersExample.Criteria criteria = calendarUsersExample.createCriteria();
        criteria.andEmailEqualTo(email);
        List<CalendarUsers> usersList = calendarUsersMapper.selectByExample(calendarUsersExample);
        if (usersList.size() == 0) {
            return null;
        } else if (usersList.size() > 1) {
            throw new DirtyDataException("发现多条email一样的用户信息");
        } else {
            CalendarUser calendarUser = new CalendarUser();
            CalendarUsers calendarUsers = usersList.get(0);
            BeanUtils.copyProperties(calendarUsers, calendarUser);
            return calendarUser;
        }
    }

    public List<CalendarUser> findUsersByPartialEmail(String email){
        CalendarUsersExample calendarUsersExample = new CalendarUsersExample();
        CalendarUsersExample.Criteria criteria = calendarUsersExample.createCriteria();
        criteria.andEmailLike("%"+email+"%");
        List<CalendarUsers> usersList = calendarUsersMapper.selectByExample(calendarUsersExample);
        List<CalendarUser> ret = new ArrayList<>();
        CalendarUser calendarUser;
        for(CalendarUsers calendarUsers : usersList){
            calendarUser = new CalendarUser();
            BeanUtils.copyProperties(calendarUsers,calendarUser);
            ret.add(calendarUser);
        }
        return ret;
    }

    /**
     * 根据用户id，查询此用户的所属角色
     *
     * @param userId 用户id
     * @return
     */
    @Override
    public List<Role> findUserRoles(Long userId) {
        List<personal.lijun.skeleton.springcloud.dataaccess.data.Role> roleList = calendarUsersMapper.findUserRoles(userId);
        personal.lijun.skeleton.springcloud.dataaccess.data.Role dbRole;
        Role role;
        List<Role> retList = new ArrayList<>(roleList.size());
        for(int i=0;i<roleList.size();i++){
            dbRole = roleList.get(i);
            role = new Role();
            BeanUtils.copyProperties(dbRole,role);
            retList.add(role);
            roleList.set(i,null);
        }
        return retList;
    }

    /**
     * 根据登录账号，获取登录人信息
     *
     * @param email
     * @return
     */
    @Override
    public CalendarUser getByLoginName(String email) {
        return findUserByEmail(email);
    }

    /**
     * 修改用户密码
     *
     * @param userId
     * @param salt
     * @param password
     * @return
     */
    @Override
    public int changePassword(long userId, String salt, String password) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(4);
        String encodedPassword = encoder.encode(password);
        CalendarUsers calendarUsers = new CalendarUsers();
        calendarUsers.setId(userId);
        calendarUsers.setPassword(encodedPassword);
        return calendarUsersMapper.updateByPrimaryKeySelective(calendarUsers);
    }


    /**
     * 分页查询用户信息
     * @param name 用户名
     * @param locked 是否锁定
     * @param sort 排序表达式
     * @param offset 查询第几页
     * @param limit 每页大小
     * @return
     */
    public List<CalendarUser> getUserList(String name,  Boolean locked,
                                          String sort, int offset, int limit){

        CalendarUsersExample example = new CalendarUsersExample();
        example.setOrderByClause(sort);
        CalendarUsersExample.Criteria criteria = example.createCriteria();
        criteria.andFirstNameEqualTo(name);
        PageHelper.startPage(offset,limit);

        Page<CalendarUsers> calendarUsersList = (Page<CalendarUsers>)calendarUsersMapper.selectByExample(example);
        Page<CalendarUser> ret = new Page<>(calendarUsersList.getPageNum(),calendarUsersList.getPageSize());
        ret.setTotal(calendarUsersList.getTotal());
        CalendarUsers calendarUsers;
        CalendarUser calendarUser;

        for(int i=0;i<calendarUsersList.size();i++){
            calendarUsers = calendarUsersList.get(i);
            calendarUser = new CalendarUser();
            BeanUtils.copyProperties(calendarUsers,calendarUser);
            calendarUsersList.set(i,null);
            ret.add(calendarUser);
        }
        return ret;
    }
}